// pages/sign-in/sign-in.js
const {
  getMonthSignInRecords,
  getContinuousDays,
  signIn,
  getSignConfig,
} = require("../../api/integral.js");

Page({
  data: {
    // 当月签到记录
    signInRecords: [],
    // 连续签到天数
    continuousDays: 0,
    // 当前日期
    currentDate: "",
    // 当月日历数据
    calendarData: [],
    // 是否已签到
    hasSignedToday: false,
    // 加载状态
    loading: false,
    // 签到按钮状态
    signInLoading: false,
    // 本次签到获得积分
    rewardPoints: 0,
    // 签到成功动画
    showRewardAnimation: false,
    // 签到配置
    signConfig: {
      days: [],
      points: [],
    },
    // 连续签到奖励规则
    rewardRules: [],
  },

  onLoad() {
    // 获取当前日期
    const today = new Date();
    const currentDate = this.formatDate(today);
    this.setData({
      currentDate: currentDate,
    });

    // 加载签到数据
    this.loadSignInData();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadSignInData();
  },

  // 加载签到数据
  async loadSignInData() {
    try {
      this.setData({ loading: true });

      // 并行获取所有签到相关数据
      const [recordsRes, continuousRes, configRes] = await Promise.all([
        getMonthSignInRecords(),
        getContinuousDays(),
        getSignConfig(),
      ]);

      // console.log("当月签到记录:", recordsRes);
      // console.log("连续签到天数:", continuousRes);
      // console.log("签到配置:", configRes);

      if (recordsRes && recordsRes.code === 0) {
        const signInRecords = recordsRes.data || [];
        this.setData({
          signInRecords: signInRecords,
          hasSignedToday: signInRecords.includes(this.data.currentDate),
        });
      }

      if (continuousRes && continuousRes.code === 0) {
        this.setData({
          continuousDays: continuousRes.data || 0,
        });
      }

      if (configRes && configRes.code === 0) {
        const config = configRes.data || {};
        const { days = [], points = [] } = config;

        // 生成奖励规则
        const rewardRules = days.map((day, index) => ({
          day: day,
          points: points[index] || 0,
        }));

        this.setData({
          signConfig: config,
          rewardRules: rewardRules,
        });
      }

      // 生成当月日历数据
      this.generateCalendarData();
    } catch (error) {
      console.error("加载签到数据失败:", error);
      wx.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 生成当月日历数据
  generateCalendarData() {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth();
    const currentDate = this.formatDate(today);

    // 获取当月第一天和最后一天
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();

    // 获取当月第一天是星期几
    const firstDayWeek = firstDay.getDay();

    const calendarData = [];

    // 添加上个月的空白日期
    for (let i = firstDayWeek - 1; i >= 0; i--) {
      const date = new Date(year, month, -i);
      calendarData.push({
        date: this.formatDate(date),
        day: date.getDate(),
        isCurrentMonth: false,
        isToday: false,
        isSigned: false,
      });
    }

    // 添加当月的日期
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(year, month, day);
      const dateStr = this.formatDate(date);
      const isToday = dateStr === currentDate;
      const isSigned = this.data.signInRecords.includes(dateStr);

      calendarData.push({
        date: dateStr,
        day: day,
        isCurrentMonth: true,
        isToday: isToday,
        isSigned: isSigned,
      });
    }

    // 添加下个月的空白日期，使日历完整
    const remainingDays = 42 - calendarData.length; // 6行 × 7天 = 42
    for (let day = 1; day <= remainingDays; day++) {
      const date = new Date(year, month + 1, day);
      calendarData.push({
        date: this.formatDate(date),
        day: date.getDate(),
        isCurrentMonth: false,
        isToday: false,
        isSigned: false,
      });
    }

    this.setData({
      calendarData: calendarData,
    });
  },

  // 签到按钮点击事件
  async onSignInTap() {
    if (this.data.hasSignedToday) {
      wx.showToast({
        title: "今日已签到",
        icon: "none",
      });
      return;
    }

    if (this.data.signInLoading) {
      return;
    }

    try {
      this.setData({ signInLoading: true });

      const res = await signIn();
      // console.log("签到结果:", res);

      if (res && res.code === 0) {
        const { consecutiveDays, rewardPoints } = res.data || {};

        // 显示签到成功提示
        // wx.showToast({
        //   title: `签到成功，获得${rewardPoints}积分`,
        //   icon: "success",
        //   duration: 2000,
        // });

        // 更新签到状态
        this.setData({
          hasSignedToday: true,
          continuousDays: consecutiveDays || this.data.continuousDays + 1,
          rewardPoints: rewardPoints || 0,
          showRewardAnimation: true,
        });

        // 将今天添加到签到记录中
        const newRecords = [...this.data.signInRecords, this.data.currentDate];
        this.setData({
          signInRecords: newRecords,
        });

        // 重新生成日历数据
        this.generateCalendarData();

        // 3秒后隐藏奖励动画
        setTimeout(() => {
          this.setData({
            showRewardAnimation: false,
          });
        }, 3000);
      } else {
        wx.showToast({
          title: res.message || "签到失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("签到失败:", error);
      wx.showToast({
        title: "签到失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({ signInLoading: false });
    }
  },

  // 格式化日期为 YYYY-MM-DD 格式
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },
});
